<template>
<div>
  <div v-show="isShowChatContainer && isComplete" class="pageContent" :class="tabIndex==2&& hasToken ? 'pageContentGre' : ''">
    <view class="tabList">
      <view class="tabItem" :class="{'tabSelect' : tabIndex==index}" @click="toDetail(index)"
      v-for="(item,index) in userList" :key="index">
          {{item.name}}
      </view>
    </view>
    <view class="loginM" v-if="!hasToken && 1">
      <image class="loginMIco" :src="images +'/loginMIco.png'" />
      <button class="btOne loginMBt" @click="loginRed">请先验证身份登录</button>
    </view>
    <canvas class="imageTest" canvas-id="canvas" v-show="tabIndex==0 && !isQrExpire && hasToken" @click="qrCodeTempNew"></canvas>
    <view class="imageTest" v-if="tabIndex==0 && isQrExpire && hasToken" @click="qrCodeTempNew">
      <image class="imageTestBack" :src="images +'/codeDefault.png'" />
      <view class="imageTestLod"></view>
      <image class="centerAbs imageTestIc" :src="images +'/refreshIcon.png'" />
      <view class="centerAbs imageTestRe">点击刷新</view>
      <view class="centerAbs imageTestNo">原通行码已失效</view>
    </view>
    <view class="code" v-if="tabIndex==0 && hasToken">
      <view class="codeMain">
        <view class="codeTime">开门密码：{{codeText || '暂无'}}</view>
        <view class="imageTestMa" ></view>
        <!-- <canvas class="imageTest" canvas-id="canvas"></canvas> -->
        <view class="codeRefMa">3分钟后自动失效<text class="codeRef" @click="qrCodeTempNew">手动刷新</text> </view>
        <view class="codeTip">二维码对准扫码处 间距在0.8米内</view>
      </view>
      <view class="codeMes">
        <image class="codeMesIc" :src="localImages +'/messageIcon.png'" />
        <swiper class="codeMesNo"  autoplay='true' interval="4000">
          <swiper-item v-for="(item,index) in noList" :key="index">
            {{item.content || '物业消息图文标题'}}
          </swiper-item>
        </swiper>
      </view>
      <view class="codeMesAd">
        <swiper class="codeMesSw" indicator-dots="1" autoplay='true' interval="4000"
        indicator-active-color="#1086FF">
          <swiper-item v-for="(item,index) in adList" :key="index">
            <image v-if="item.pictureUrl" class="codeMesSwIm" :src="item.pictureUrl ||adListPicUrl" mode="widthFix"
             @click="showPhoto(item.pictureUrl)"/>
            <block v-if="item.mediaUrl">
              <image v-if="item.mediaUrl" class="codeMesSwIm" :src="item.thumbnailUrl ||adListPicUrl" mode="widthFix"
               @click="goMedia(item.mediaUrl)"/>
            </block>
          </swiper-item>
        </swiper>
      </view>
    </view>

    <view class="come" v-if="tabIndex==1 && hasToken">
      <view class="comeCon">
        <view class="comeReg"><text class="memberItSt">*</text>来访目的</view>
        <view class="comeTyList" v-if="1">
          <view class="comeType"  @click="comeListCli(index)" v-for="(item,index) in comeList" :key="index">
            <image class="comeTypeIcon" :src="item.comeUrl"/>
            <view class="comeTypeMsg" :class="{'comeTypeSel' : comeIndex==index}">{{item.visitPurposeName || '亲朋好友'}}
            </view>
          </view>
        </view>
        <view class="comeTime">
          <text class="memberItSt">*</text>
          <text class="comeTimeBol">访客姓名</text>
          <view class="comeRight">
            <input class="memberItIn" v-model="visitorName" placeholder="填写访客姓名与身份证上名字一致" placeholder-class="inputPlaceHold"/>
          </view>
        </view>
        <view class="comeTime">
          <text class="memberItSt">*</text>
          <text class="comeTimeBol">同行人数</text>
          <view class="comeRight">
            <picker class="comePicMain" :value="periodIndex" :range="period" range-key="name" @change="choose" id="period" data-name="period">
              <view class="comePicVie">{{period[periodIndex].name}}</view>
              <view class="comePicDel"></view>
            </picker>
          </view>
        </view>
        <view class="comeTime">
          <text class="memberItSt">*</text>
          <text class="comeTimeBol">来访日期</text>
          <view class="comeRight">
            <picker class="comePic" mode="date" :value="date" @change="choose" id="date">
              <view class="comePicVie comeDefault" v-if="date=='' ">请选择日期</view>
              <view class="comePicVie" v-else>{{date}}</view>
              <image class="comePicDatIm" :src="localImages +'/date.png'"/>
            </picker>
           <!-- <picker class="comePic" mode="time" :value="time" @change="choose" id="time">
              <view class="comePicVie comeDefault" v-if="time=='' ">请选择时间</view>
              <view class="comePicVie" v-else>{{time}}</view>
              <image class="comePicDatIm" :src="localImages +'/date.png'"></image>
            </picker> -->
          </view>
        </view>
        <view class="comeTime">
          <text class="memberItSt">*</text>
          <text class="comeTimeBol">通行次数</text>
          <view class="comeRight">
            <picker class="comePicMain" :value="comeTimeIndex" :range="comeTime" range-key="name" @change="choose" id="comeTime">
              <view class="comePicVie">{{comeTime[comeTimeIndex].name}}</view>
              <view class="comePicDel"></view>
            </picker>
          </view>
        </view>
        <view class="comeTime"  id="comeTimeBol">
          <text class="memberItSt empty">*</text>
          <text class="comeTimeBol">车牌号码</text>
          <view class="search-car-input" @click="carInputClick">
              <view class="car-input">
                  <view class="energy" v-show="plateNum.length>7">
                    新能源
                  </view>
                  <view class="car-input-text" :class="{ 'active': plateNum }">
                      {{plateNum || '填写车牌号方便车辆通行'}}
                  </view>

                  <view class="cursor" v-show="isCursor">
                      <image :src="cursor" mode="" />
                  </view>
              </view>
          </view>
        </view>

        <!-- 引用车牌组件 -->
        <plateNumber ref="plate" v-model="plateNum" @showOrHide="showOrHide"></plateNumber>
        <button class="btOne" :class="comeIndex==-1 ? 'btDefalt' : ''" @click="commitTamp">生成通行码</button>
      </view>
      <view class="comeMes">
        <image class="codeMesIc" :src="localImages +'/messageIcon.png'" />
        使用说明:生成通行码后将保存在手机相册发送给您的访客即可通行使用.
      </view>
    </view>

    <view v-if="tabIndex==2 && hasToken">
      <view class="remote" v-if="doorList.length && isComplete">
        <view class="remoteMain" @click="doorListCli(index)"
        v-for="(item,index) in doorList" :key="index">
          <image class="remoteBac" v-show="doorIndex==index" :src="images +'/selectGate.png'" />
          <image class="remoteIco" :src="localImages +'/damen.png'"/>
          <view class="remoteGate">{{item.gatePostName || '悦江苑 东门'}}</view>
          <!-- <view class="remoteName">{{item.equipmentName || '设备名称'}}</view> -->
          <image class="remoteSel" v-if="doorIndex==index" :src="localImages +'/doorSelect.png'" />
        </view>
        <!-- <view class="roomMov" v-if="1" @touchstart="buttonStart"> -->
        <view class="roomMov" v-if="1" @click="doDoor(0)">
          <image class="roomMovTe" :src="images +'/roomMovIc.png'" />
          <view class="roomMovMsg">开门</view>
        </view>
        <view class="roomMov reboot" v-if="1" @click="doDoor(1)">
          <image class="roomMovTe" :src="images +'/roomMovIc.png'" />
          <view class="roomMovMsg">重启</view>
        </view>
      </view>
      <view class="appEmp" v-if="!doorList.length && isComplete">
        <image class="appEmpIcon" :src="images +'/appEmpty.png'" mode="widthFix"></image>
        <view class="appEmpMsg">～当前门禁设备已离线～</view>
      </view>
    </view>
  </div>
  <div v-show="!isShowChatContainer && isComplete"><Calling ref="callingDom" /></div>
  <vant-calendar v-if="0" type="range" bind:close="onClose" bind:confirm="onConfirm"/>
</div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import Calling from '../../components/calling'
import { throttle } from '../../utils/index'
import { genTestUserSig } from '../../../static/utils/GenerateTestUserSig'
import config from '../../../static/config.js'
import drawQrcode from '../../../static/utils/weapp.qrcode.esm.js'
import util from '../../../static/utils/util.js'
import plateNumber from '../../components/plateNumber.vue'
// import vant-calendar from '../../../static/vant/calendar/index'
export default {
  data () {
    return {
      TRTCCallingComponent: null,
      modalVisible: false,
      conversation: {},
      isShowChatContainer: true,
      images: config.images,
      localImages: config.localImages,
      mountedCount: 0,
      userList: [{name:'通行码'},{name:''},{name:'远程开门'}],
      // userList: [{name:'通行码'},{name:'远程开门'}],
      tabIndex:0,
      // doorList: [{name:'悦江苑 东门'},{name:'悦江苑 南门'},{name:'悦江苑 北门'}],
      doorList: [],
      doorIndex:-1,
      comeList: [{name:'通行码'},{name:'上门服务'},{name:'装修'},{name:'求职面试'},
      {name:'求职面试'},{name:'搬家搬运'},{name:'中介看房'},{name:'更多'},],
      comeIndex: -1,
      formData: {
        personCount: '',
        date: '',
        time: '',
      },
      date: '',
      time: '',
      codeText:'888888',
      qrCodeTempTe:'888888',
      // qrCodeTempTe:'MLk1UTrsS0Y=',
      hasToken:false,
      isComplete:false,
      room:'',
      adList:[
        {pictureUrl:'https://www.anbotcloud.cn/minIO/picture/owner/2021-04-28/1619616094460.jpg'},
        {pictureUrl:'https://www.anbotcloud.cn/minIO/picture/owner/2021-04-28/1619616107096.jpg'},
      ],
      adListPicUrl:'https://www.anbotcloud.cn/minIO/picture/owner/2021-04-28/1619616094460.jpg',
      noList:[{content:'关于2021年部分节假日安排的通知'},{content:'关于2021年部分物业的通知'}],
      period: [{ id: 0, name: '0' }, { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' },{ id: 4, name: '3人以上' },],
      periodIndex: 0,//同行人数
      comeTime: [{ id: 1, name: '1次' }, { id: 0, name: '不限' },],
      comeTimeIndex: 0,//通行次数
      visitorName:'',
      timer:'',
      isHide:false,
      isAppHide:false,
      isRecording:false,
      plateNum: '', //输入的车牌号
      isCursor: false, //是否显示焦点
      isQrExpire: false, //二维码是否过期
      intervalCount: 0,
    }
  },
  computed: {
    ...mapState({
      allConversation: state => state.conversation.allConversation,
      isSdkReady: state => state.global.isSdkReady,
      isCalling: state => state.global.isCalling,
      initTRTCCalling: state => state.global.initTRTCCalling,
      currentPage: state => state.global.currentPage
    }),
    ...mapGetters(['totalUnreadCount', 'myInfo'])
  },
  // 消息列表下拉
  onPullDownRefresh () {
    // throttle(this.handleLogin(), 1000) //throttle限流避免重复操作
    util.tottleOne(()=>{
      var token=wx.getStorageSync('token');
      if(token) {
        this.qrCodeTemp();
        this.noticeList();
        this.gateList()
      }
    })
    //测试-检查权限
    // this.checkScope();

    wx.stopPullDownRefresh()
  },
  created() {
    console.warn('===index==created执行===')
    console.warn('this.isSdkReady',this.isSdkReady)
    this.handleLogin()
    var token=wx.getStorageSync('token');
    if(token) {
    }
    // util.socketTest();
  },
  mounted () {
    console.warn('mounted执行次数：')
      // this.callLogin()
      var timer=setInterval(()=>{
        console.warn('interval执行次数：',++this.intervalCount)
        //在sdk初始化完成后，TRTCCalling组件用户登录
        if(this.isSdkReady) {
          this.callLogin()
          clearTimeout(timer);
          timer = null;
        }
        if(this.intervalCount>5) {
          clearTimeout(timer);
          timer = null;
        }
      },500)

  },
  onLoad() {
    console.warn('onLoad')
    if (!this.isSdkReady) {
      // wx.showLoading({ title: '', mask: true,duration:500 })
    }
    //0.4秒后开始加载页面
    setTimeout(()=>{this.isComplete=true},300)
    // var token="eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTg0NzI0NTYsImlzcyI6IjkyIiwic3ViIjoiMyIsImF1ZCI6IjMifQ.0wa_y3sSLDRC4MoDW0o1Ydp4ka6Q8EUdu4kYDODofaM";
    // var token=wx.setStorageSync('token',token);
    // var room=
    // {
    //   "roleId": 21,
    //   "name": "阿根",
    //   "ownerId": 92,
    //   "projectId": 1,
    //   "roomId": 3,
    //   "roomName": "2007",
    //   "roomInfo": "湘江世纪城-一期-3栋-2004室"
    // }
    var token=wx.getStorageSync('token');
    this.showQrcode()
    if(token) {
      var room = wx.getStorageSync('room');
      this.room=room;
      this.purposeAll();
      this.qrCodeTemp();
      this.noticeList();
    }else {

    }

    //测试-检查权限:折中处理，在第一次进入小程序就获取权限，用于下次视频通话。原因是第一次获取权限并不会立即生效，导致视频通话连接异常
    // this.checkScope();

    //开启分享朋友圈
    wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
    });

  },
  onHide() {
    console.warn('index=onHide')
    console.warn('currentPage',this.currentPage)
    var pages = getCurrentPages()
    this.isHide=true;
    this.carClose();//关闭车牌键盘

    this.recoverLight();

    //停止二维码过期状态定时任务
    this.stopCode();
  },
  onShow() {
    this.isHide=false;
    if(this.isAppHide){
      console.warn('小程序最小化=》页面回显')
      this.isAppHide=false
    }

    console.warn('this.initTRTCCalling=',this.initTRTCCalling,'this.isSdkReady=',this.isSdkReady)
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    // 当接收端在不在index页时在onshow钩子中监听isCalling变化，控制tabBar
    this.updatePageInfo(this.isCalling)
    var token=wx.getStorageSync('token');
    var room = wx.getStorageSync('room');
    if(token) {
      this.hasToken=true
      // this.qrCodeTemp();
      // this.noticeList();
      this.gateList()
    }else {
      this.hasToken=false
    }
    var self=this;
    //调节当前屏幕亮度
    wx.getScreenBrightness({
      success(res){
        console.warn('success',res)
        wx.setStorageSync('screenBri', res.value);
        if(self.tabIndex==0 && token){
          wx.setScreenBrightness({value:0.8})
        }
      }
    })


    //默认选择当天
    var dateString=new Date().format('yyyy/MM/dd');
    this.date=dateString;

    // this.testCall();

    // this.carInputClick(); // 测试车牌键盘

  },
  onUnload(){
    console.warn('onUnload')
    this.recoverLight();
    //停止二维码过期状态定时任务
    this.stopCode();
  },
  components: {
    Calling,
    plateNumber
  },
  methods: {
    buttonStart(e){
      console.warn('buttonStart',e)
    },
    //模拟打开接听视频页面
    testCall(){
      this.hideChatContainer()
      this.$refs.callingDom.handleInvited()
    },
    //TRTCCalling组件用户登录
    callLogin(){
      //this.initTRTCCalling 不要判断，在mounted只会执行一次
      // if (this.initTRTCCalling && this.isSdkReady) {
      if (this.isSdkReady) {
        console.warn('this.initTRTCCalling',this.$mp.page.selectComponent('#TRTCCalling-component'))
        wx.$TRTCCallingComponent = this.$mp.page.selectComponent('#TRTCCalling-component') //选取TRTCCalling组件
        this.$bindTRTCCallingRoomEvent(wx.$TRTCCallingComponent) // TRTCCalling事件监听
        try{
          wx.$TRTCCallingComponent.login()
          this.$store.commit('setInitTRTCCalling', false)
        }catch(err){
          console.warn('catch')
        }finally {
          console.warn('finally')
        }
       }
    },
    // 点击登录进行初始化
    handleLogin() {
      var userMsg=wx.getStorageSync('userMsg');
      if(userMsg) {
        var userID = userMsg.im_userId
        // case1: 要登录的用户是当前已登录的用户，则直接跳转即可
        console.warn('this.myInfo',this.myInfo,this.myInfo.userID,userID)
        if (this.myInfo.userID && userID === this.myInfo.userID) {
          return
        }
        // case3: 正常登录流程
        this.login(userMsg)
      }else {
      }
    },
    login(userMsg) {
      console.warn('login=login')
      // var userID = 'user2'
      // let userSig = genTestUserSig(userID).userSig
      var userID = userMsg.im_userId
      var userSig = userMsg.userSig
      wx.$app.login({
        userID:userID,
        userSig: userSig
      }).then((res) => {
        console.warn('login=',res)
        this.$store.commit('setRtcConfig', {userID: userID, userSig: userSig, sdkAppID: wx.$sdkAppID})
      }).catch(() => {
      })
    },

    handleModalShow() {
      this.modalVisible = !this.modalVisible
    },
    handleConfirm() {
      this.handleModalShow()
      this.deleteConversation(this.conversation)
    },
    showChatContainer() {
      this.isShowChatContainer = true
    },
    hideChatContainer() {
      this.isShowChatContainer = false
    },
    updatePageInfo(flag) {
      if (flag) {
        wx.setNavigationBarTitle({title: ''})
        wx.hideTabBar()
      } else {
        wx.setNavigationBarTitle({title: '世纪金源物业'})
        wx.showTabBar()
      }
    },

    toDetail(id) {
      this.tabIndex=id
      var token=wx.getStorageSync('token');
      if(token){
        if(id==0){
          wx.setScreenBrightness({value:0.8})
        }else if(id==1){
          this.recoverLight();
        }else if(id==2){
          this.gateList()
          this.recoverLight();
        }
      }

    },
    //来访目的
    comeListCli(id) {
      this.comeIndex=id
    },
    doorListCli(id) {
      this.doorIndex=id
    },
    choose(e) {
      var e=e.mp
      console.warn('choose=>',e)
      var value = e.detail.value;
      var key = e.currentTarget.id;
      this.formData[key]=value
      if('date'==key){
        //判断时间：小于今天，提示用户
        value = value.replace(/-/g, "/");
        var selectTime=new Date(value).getTime()
        var nowTime=new Date().getTime()
        var diffTime=selectTime-nowTime
        console.warn('diffTime',diffTime)
        if(diffTime<-24*60*60*1000) {
          wx.showToast({
            title: "请选择有效的来访日期",
            icon: 'none'
          });
          this.date = ''
        }else {
          this.date = value
        }
      }else if('time'==key){
        this.time = value
      }else if('period'==key){
        console.warn(this.period[value].name)
        this.periodIndex=value;
      }else if('comeTime'==key){
        console.warn(this.comeTime[value].name)
        this.comeTimeIndex=value;
      }
    },
    // 显示二维码
    showQrcode() {
      let systemInfo = wx.getSystemInfoSync();
      let unit = systemInfo.windowWidth / 375;
      var text = this.qrCodeTempTe;
      drawQrcode({
        width: 240*unit,
        height: 240*unit,
        canvasId: 'canvas',
        text: text,
      })
    },
    //业主获取通行二维码和通行密码
    qrCodeTemp(isRefresh=false) {
      var roomId = this.room.roomId;
      // var url='/UserServer/owner/qrCode/qrCodeTemp'
      // /owner/qrCode/staffQrCodeTemp 物业获取通行二维码和通行密码
      var url='/UserServer/mini/staff/staffQrCodeTemp'
      var params={
        // roomId :roomId
      }
      util.wxRequestPro(url,params).then((res)=>{
        console.warn('qrCodeTemp=',res,res.param)
        if(res.param) {
          var param=res.param
          this.codeText=param.passwordTemp
          this.qrCodeTempTe=param.qrCodeTemp
           console.log('isRefresh=',isRefresh,'this.isQrExpire=',this.isQrExpire)
          if(isRefresh){
            //过期刷新
            //延时0.5秒，释放二维码过期状态，防止重启websocket，导致此时接受不到消息
            if(this.isQrExpire){
              setTimeout(()=>{this.isQrExpire=false},500)
            }else {
              //主动刷新，此时还没有过期。延迟0.5s重置基数时间为1，防止触发重启websocke
              setTimeout(()=>{this.mountedCount=1;},300)
            }
          }else {
             setTimeout(()=>{this.startCode();},100)
          }
          this.showQrcode()
        }
      })
    },
    qrCodeTempNew(){
      var room = this.room;
      wx.showToast({
        title: "刷新中…",
        icon: 'none'
      });
      this.qrCodeTemp(true);
      // if(room) {
      //   this.qrCodeTemp(true);
      // }else {
      //   wx.showToast({
      //     title: "当前账号尚未绑定房屋信息",
      //     icon: 'none'
      //   });
      // }
    },
    //获取广告与物业通知
    noticeList() {
      var projectId = this.room.projectId;
      var url='/UserServer/advertise/noticeList'
      var params={
        // projectId :projectId
      }
      util.wxRequestPro(url,params).then((res)=>{
        console.warn('noticeList',res)
        if(res.param) {
          var param=res.param
          var adList=[];
          var noList=[];
          param.map((value,index,array)=>{
            // value['pictureUrl']=config.IMAGE_APIHOST+value.pictureUrl
            if(value.type==1){
              if(value.pictureUrl){
                value.pictureUrl=config.IMAGE_APIHOST+value.pictureUrl
              }
              if(value.thumbnailUrl){
                value.thumbnailUrl=config.IMAGE_APIHOST+value.thumbnailUrl
              }
              adList.push(value)
            }else if(value.type==2) {
              noList.push(value)
            }
          })
          this.adList=adList;
          this.noList=noList;
        }
      })
    },
    // /mini/gate/staffGateList 获取该住户的门禁列表
    gateList() {
      var url='/UserServer/mini/gate/staffGateList'
      var params={
        status:1
      }
      util.wxRequestPro(url,params).then((res)=>{
        if(res.param) {
          var param=res.param
          this.doorList=param;
        }
      })
    },
    loginRed(){
      util.getUserProfile();
    },
    //访客目的列表
    purposeAll() {
      var params={}
      var url='/UserServer/system/purpose/all'
      util.wxRequestPro(url,params).then((res)=>{
        if(res.param) {
          var param=res.param.data
          param.map((item,index)=>{
             item['comeUrl']=config.images+'/comeUrl'+index+'.png'
             return item;
          })
          this.comeList=param
        }
      })
    },
    commitTamp() {
        util.tottleOne(()=>{
          console.warn('tottleOne')
          // wx.redirectTo({url:'/pages/subMe/comeCode/main'})
           this.submit()
        })
        // this.submit()
    },
    submit(){
      var status = this.validation() || false;
      if(status) {
          var params={
            "visitPurposeId":this.comeList[this.comeIndex].visitPurposeId,
            "personNumber":this.period[this.periodIndex].id,
            "roomId":this.room.roomId,
            "visitDate":this.date,
            "limitPassNumber":this.comeTime[this.comeTimeIndex].id,
            "visitorName":this.visitorName
          };
          if(this.plateNum){
            params['visitorPlate']=this.plateNum;
          }
        // var params={"visitPurposeId":2,"personNumber":2,"roomId":6,"visitDate":"2021-12-31 12:00:00","limitPassNumber":1,"visitorName":"agen"}
        util.wxRequestPro('/UserServer/owner/qrCode/invitation',params,"PUT")
        .then((res)=>{
          console.warn('ownerRoomList=then',res)
          var param=res.param;
          params['qrCodeTemp']=param.qrCodeTemp
          params['passwordTemp']=param.passwordTemp
          params['roomInfo']=param.roomInfo
          if(param.visitorPlate){
            params['visitorPlate']=param.visitorPlate;
          }
          console.warn('params',params)
          wx.showToast({
            title: '生成成功',
            icon: 'none'
          })
          this.onReset();
          // var json=JSON.stringify(params);
          var json=encodeURIComponent(JSON.stringify(params));//函数可把字符串作为 URI 组件进行编码
          wx.navigateTo({url:'/pages/subMe/comeCode/main?json='+json})
        }).catch((res)=>{
          console.warn('ownerRoomList'+res)
          if(res.statusCode==400) {
            wx.showToast({
              title: '生成错误',
              icon: 'none'
            })
          }
        })
      }
    },
    onReset(){
      this.comeIndex=-1;
      this.visitorName='';
      this.periodIndex=0;
      this.comeTimeIndex=0;
      this.date='';
      this.plateNum='';
      this.$refs.plate.init();//车牌键盘号码恢复初始化
    },
    validation() {
      if (this.comeIndex === -1) {
        wx.showToast({
            title: "请选择来访目的",
            icon: 'none'
        });
        return false;
      }
      if (this.visitorName == "") {
        wx.showToast({
            title: "请输入访客姓名",
            icon: 'none'
        });
        return false;
      }
      if (this.date == "") {
        wx.showToast({
            title: "请选择日期",
            icon: 'none'
        });
        return false;
      }
      if (this.plateNum != "") {
        var tel = this.plateNum; //
        if(tel.length<7) {
          wx.showToast({
              title: "请输入正确格式的车牌号",
              icon: 'none'
          });
          return false;
        }
      }
      return true;
    },
    //订阅消息
    onSub(){
      return new Promise((resolve,reject)=>{
        wx.requestSubscribeMessage({
          tmplIds: config.tmplIds,
          success (res) {
            console.warn('res',res)
            var value=Object.values(res);
            if(value[0]=='accept') {
              resolve()
              wx.setStorageSync('hasSub', 1);
            }else{
              wx.setStorageSync('hasSub', 2);
            }
          },
          fail (res) {
            console.warn('fail=res',res)
            if(res.errCode==20004) {
              // 用户关闭了主开关，无法进行订阅
              wx.showToast({
                  title: "请在设置中打开通知管理开关",
                  icon: 'none',
                  duration: 2000,
              });
            }
            wx.setStorageSync('hasSub', 2);
          },
        })
      })
    },
    //获取用户订阅消息开关
    onSubSet(){
      console.warn('onSubSet')
      var self=this;
      var hasSub=wx.getStorageSync('hasSub');
      var token=wx.getStorageSync('token');
      this.systemSetting().then((res)=>{
        if(res.visitorNotifySwitch==0 && !hasSub ){
          self.onShowModal()
        }
      })

      // wx.getSetting({
      //   withSubscriptions :true,
      //   success(res) {
      //     console.warn('getSetting=res',res)
      //     //订阅消息总开关,提醒用户打开订阅消息
      //     if(!res.subscriptionsSetting.mainSwitch) {
      //       // self.onShowModal()
      //     }
      //   }
      // })
    },
    onShowModal(){
      var self=this;
      wx.showModal
      ({
        title: '消息订阅提示',
        content: '若取消将无法接收门禁终端PAD发起的远程呼叫请求，建议订阅。',
        cancelColor: "#999999",
        confirmColor: "#1086FF",
        confirmText: '订阅',
        cancelText: '取消',
        success (res) {
          if (res.confirm) {
            self.onSub();
          } else if (res.cancel) {
            wx.setStorageSync('hasSub', 2);
          }
        }
      })
    },
    doDoor(type=0) {
      if(this.doorIndex==-1){
        wx.showToast({
          title: '请选择门禁',
          icon: 'none'
        })
        return
      }
      util.tottleOne(()=>{
        console.warn('tottleOne')
        // wx.redirectTo({url:'/pages/subMe/comeCode/main'})
        if(type==0){
          wx.showLoading({ title: '开门中...', mask: true,duration:1200 })
          this.remoteControl()
        }else if(type==1){
          wx.showLoading({ title: '重启中...', mask: true,duration:1200 })
          this.rebootControl()
        }

      },1500)
      // this.remoteControl()
    },

    //远程开门
    remoteControl(){
      var equipmentId= this.doorList[this.doorIndex].equipmentId || 11;
      var phoneNumber=wx.getStorageSync('phone');
      //获取业主该手机号绑定的房屋列表
      var params={equipmentId :equipmentId}
      var paramsUrl=util.stringifyQs(params)
      util.wxRequestPro('/UserServer/mini/gate/remoteControl?'+paramsUrl,{},"POST")
      .then((res)=>{
        //开门指令，没有成功回调，
        // wx.showToast({
        //     title: '开门成功',
        //     icon: 'none'
        // })
      }).catch((res)=>{
        if(res.statusCode==400) {
        }
      })
    },
    //重启设备接口
    rebootControl(){
      var equipmentId= this.doorList[this.doorIndex].equipmentId || 11;
      var phoneNumber=wx.getStorageSync('phone');
      //获取业主该手机号绑定的房屋列表
      var params={equipmentId :equipmentId}
      var paramsUrl=util.stringifyQs(params)
      util.wxRequestPro('/UserServer/mini/gate/reboot?'+paramsUrl,{},"POST")
      .then((res)=>{
        //重启设备接口成功回调，
      }).catch((res)=>{
        if(res.statusCode==400) {
        }
      })
    },
    systemSetting() {
      return new Promise((resolve,reject)=>{
        var params={
          roomId:this.room.roomId,
          }
        util.wxRequestPro('/UserServer/owner/info/systemSetting',params)
        .then((res)=>{
          console.warn('systemSetting',res)
          var param=res.param;
          resolve(param)
        })
      })
    },
    showPhoto(...url){
      console.warn('showPhoto',url)
      wx.previewImage({
        current: '', // 当前显示图片的http链接
        urls: url // 需要预览的图片http链接列表
      })
    },
    goMedia(url){
      wx.navigateTo({url:'/pages/subMe/adPage/main?url='+url})
    },
    getSettingRecord(options={scope:'scope.record',content:'请前往设置页打开麦克风'}) {
      var self=this;
      return new Promise((resolve,reject)=>{
        wx.getSetting({
          success: (res) => {
            let auth = res.authSetting[options.scope]
            console.warn('scope.record=',auth,typeof auth)
            if (auth === true) { // 用户已经同意授权
              resolve(true)
            }
            else if (auth === undefined) {// 首次发起授权
              wx.authorize({
                  scope: options.scope,
                  success() {
                      resolve(true)
                  },
                  fail(res) {
                  }
              })
            }
            else if (auth === false) { // 非首次发起授权，用户拒绝过
              wx.showModal({
                title: '授权提示',
                content: options.content,
                success: (tipRes) => {
                  if (tipRes.confirm) {
                    wx.openSetting({
                      success: (settingRes) => {
                        if(settingRes.authSetting[options.scope]) {
                          resolve(true)
                        }
                        console.warn('settingRes',settingRes)
                      },
                    })
                  }
                }
              })
            }
          },
        })
      })

    },
    // 提示前往设置页
    toSettingPage(options) {
      wx.showModal({
        title: '授权提示',
        content: options.content,
        success: (tipRes) => {
          if (tipRes.confirm) {
            wx.openSetting({
              success: (settingRes) => {
                console.warn('settingRes',settingRes)
              },
            })
          }
        }
      })
    },
    //检测权限
    checkScope(){
      return new Promise((resolve, reject) => {
        var promise1=this.getSettingRecord()
        var options={scope:'scope.camera',content:'请前往设置页打开摄像头'}
        var promise2=this.getSettingRecord(options)
        Promise.all([promise1,promise2]).then(res=>{
          console.warn('Promise.all',res);
          if(res[0] && res[1]){
            console.warn('获取权限成功')
            resolve();
          }
        })
      })
    },

    inputChange(e) {
      var e=e.mp
      console.warn(e)
      var value = e.detail.value;
      var key = e.currentTarget.id;
    },

    /**
     * @desc 显示车牌选择器
     */
    carInputClick() {
      setTimeout(()=>{
        console.warn('this.$refs',this.$refs,this.$refs.plate,this.$refs.callingDom)
        this.$refs.plate.show();
      },200)
    },
    //关闭车牌键盘
    carClose() {
      if(this.$refs.plate) {
        this.$refs.plate.close();
      }
    },
    /**
     * @desc 车牌选择关闭和打开
     */
    showOrHide(falg) {
        this.isCursor = falg;
        console.warn('falg=',falg)
        if(falg) {
          this.scrollToCar();
        }else {
          wx.pageScrollTo({
          scrollTop: 0
          })
        }
    },
    //滚动屏幕显示车牌区域
    scrollToCar(){
      var query = wx.createSelectorQuery()
       //获取顶部的距离
      query.select('#comeTimeBol').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function(res){
        var top =res[0].top       // #the-id节点的上边界坐标
        wx.pageScrollTo({
        scrollTop: top
        })
      })
    },
    //离开当前页面恢复屏幕亮度
    recoverLight(){
      var screenBri=wx.getStorageSync('screenBri');
      wx.setScreenBrightness({value:screenBri})
    },
    //开启二维码过期状态定时任务
    startCode() {
      var pingTime=-1;
      util.interval(()=>{
        var ownerQrExpire=wx.getStorageSync('ownerQrExpire');
        //websocket发送二维码已经使用的消息
        // if(ownerQrExpire) {
        //   this.stopCodeShow()
        // }
        // 测试过期二维码
        // if(this.mountedCount==5){
        //   this.stopCodeOnly()
        // }
        // 8s自动重连
        if(this.mountedCount%8==0){
          var nowTime=new Date().getTime()
          console.log('nowTime-pingTime',nowTime-pingTime)
          //第一次连接,并且此时二维码不过期/距离上一次收到ping超过8s => 触发websocket重连
          if( (this.mountedCount==0 && !this.isQrExpire) || nowTime-pingTime>8*1000 ){
            console.log('===util.socketTest')
            util.socketTest((res)=>{
              if(res=='ping'){
                // console.log('ping',res)
                pingTime=new Date().getTime() //上次心跳成功的时间
              } else if(res=='ownerQrExpire') {
                //websocket发送二维码已经使用的消息
                this.stopCodeOnly()
              }
            });
          }
        }

        // 3分钟自动过期
        if(this.mountedCount>180) {
          this.stopCodeOnly()
        }
        console.log('interval执行次数-二维码：',++this.mountedCount)
      },1000)
    },
    //重置定时任务计数时间，展示过期二维码页面
    stopCodeOnly() {
      this.mountedCount=1
      this.codeText='- - - - - -'
      this.isQrExpire =true;
    },
    //停止二维码过期状态定时任务，展示过期二维码页面
    stopCodeShow() {
      this.mountedCount=0
      this.codeText='- - - - - -'
      this.isQrExpire =true;
      util.clearInterval()
    },
    //停止二维码过期状态定时任务
    stopCode() {
      this.mountedCount=0
      this.isQrExpire =false;
      util.clearInterval()
    },
  },

  watch: {
    currentPage(newVal) {
      if (newVal) {
      }
    },

    isHide(newVal) {
      var pages = getCurrentPages()
      var page= pages[pages.length - 1].route
      console.warn('isHide',newVal,pages,page,pages.length)
      if(newVal){
        if('pages/index/main'==page) {
          this.isAppHide=true
          console.warn('小程序最小化')
        }else {
          console.warn('index hide')
        }
      }
    },

    isSdkReady (newVal) {
      if (newVal) {
        console.warn('index==watch==isSdkReady',newVal)
        wx.hideLoading()
      }
    },

    isCalling (newVal) {
      // 当接收端在index页时通过监听isCalling变化，控制UI和tabBar
      if (this.currentPage === '/pages/index/main') {
        if (newVal) {
          this.hideChatContainer()
          var self=this;
          //检测权限=>拉起视频通话控件
          this.checkScope().then(()=>{
            self.$refs.callingDom.handleInvited()
          })
        }
        this.updatePageInfo(newVal)
      }
    },

    totalUnreadCount(newVal) {
      console.warn('====totalUnreadCount=未读TIM消息数量',newVal)
    }
  }
}
</script>

<style lang='stylus'>
.pageContent{
  min-height 100vh
  padding 108rpx 0rpx 0rpx 0rpx
  background $background
}
/* vant-calendar{
  position absolute
  top 100rpx
  left 0
  width 100rpx
  height 100rpx
  background-color red
} */
.code{
  padding 0rpx 30rpx 0rpx 30rpx
}
.pageContentGre{
  background $background
}
.tabList
  position fixed
  top 0
  left 0
  width 100%
  height 108rpx
  background: #FFFFFF;
  padding 30rpx 0rpx 30rpx 30rpx
  z-index 999
  /* border 1px solid #999 */
.tabItem
  display inline-block
  font-size 32rpx
  color: #333333;
  padding 0rpx 16rpx 0rpx 16rpx
  /* border 1px solid #666 */
.tabItem:nth-child(n+2){
  margin-left 30rpx
}
.tabSelect{
  font-size 34rpx
  font-weight bold
}
.loginM{
  position relative
  display flex
  flex-direction column
  align-items center
  padding 250rpx 0rpx 0rpx 0rpx
}
.loginMIco{
  width: 240rpx;
  height: 270rpx;
}
.loginMBt{
  width 70%
}
.codeMain
  display flex
  flex-direction column
  align-items center
  box-shadow: 4px 4px 22px 2px rgba(212, 212, 212, 0.39);
  width: 686rpx;
  border-radius: 10rpx;
  padding 40rpx 40rpx 60rpx 40rpx
  margin-top 20rpx
  background: #FFFFFF;
  /* border 1px solid #666 */
  .codeTime
    color #333333
    font-size 56rpx
    padding 0rpx
    font-weight: bold;
    white-space nowrap;
.codeRefMa
  font-size 32rpx
  color #666666
  margin 0rpx 0rpx 10rpx 0rpx
.codeRef
  color #1086FF
  margin-left 12rpx
.codeTip
  color #666666

.imageTestMa{
  height 600rpx;
  width 500rpx;
  margin 0rpx 0rpx 0rpx 0rpx
  /* border 1px solid cadetblue */
}
.imageTest{
  position absolute
  height 480rpx;
  width 480rpx;
  margin 0rpx 0rpx 0rpx 0rpx
  top 258rpx
  left 50%
  margin-left -240rpx
  /* border 1px solid #bbb */
}
.imageTestBack{
  position absolute
  height 100%;
  width 100%;
  /* border 1px solid #ddd */
}
.imageTestLod{
  position absolute
  height 100%;
  width 100%;
  background-color #000000
  opacity 0.6
  text-align center
  /* border 1px solid #ddd */
}
.imageTestIc{
  width: 70rpx;
  height: 62rpx;
  padding-top 20rpx
}
.imageTestRe{
  position absolute
  font-size: 32rpx;
  color #fff
  padding-top 180rpx
}
.imageTestNo{
  position absolute
  font-size: 32rpx;
  color #ccc
  padding-top 320rpx
}

.codeMes{
  display flex
  align-items center
  width: 686rpx;
  height: 60rpx;
  background: #F2F8FF;
  box-shadow: 4px 4px 22px 4px #F3F3F3, 0px 1px 0px 0px #B8DCFF;
  border-radius: 10rpx;
  font-size 24rpx
  color: #577C93;
  padding 0rpx 0rpx 0rpx 10rpx
  margin-top 20rpx
}
.codeMesIc{
  width 30rpx;
  height 30rpx;
  margin-right 10rpx
}
.codeMesAd{
  display flex
  width: 686rpx;
  height: 180rpx;
  border-radius: 10rpx;
  margin-top 20rpx
  /* background: #B8DCFF; */
}
.codeMesNo{
  width 100%
  height 100%
  padding 26rpx 0rpx 0rpx 0rpx
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
  /* border 1px solid blue */
}
.codeMesSw{
  width 100%
  height 180rpx
  /* background #0AC160 */
}
.codeMesSwIm{
  width 100%
  height 180rpx
  /* border 1px solid coral */
}
.come
  padding 20rpx 30rpx 200rpx 30rpx
  /* border 1px solid #666 */
  .comeReg
    background: #FFFFFF;
    line-height 40rpx
    font-weight bold
    padding 0rpx 0rpx 20rpx 0rpx
  .comeCon
    width: 100%;
    /* height: 833rpx; */
    background: #FFFFFF;
    box-shadow: 4px 4px 22px 2px rgba(212, 212, 212, 0.39);
    border-radius: 10rpx;
    padding 20rpx 20rpx 60rpx 20rpx
    margin 0rpx 0rpx 20rpx 0rpx
    .comeTime
      display flex
      flex-direction row
      color #333333
      height 90rpx
      line-height 90rpx
      border-bottom: 0.3px solid #DEDEDE;

.comeTyList{
  display flex
  justify-content space-around
  flex-wrap wrap
  /* outline 1px solid #f00 */
}
.comeType{
  display inline-block
  width 98rpx
  text-align center
  margin 0rpx 0rpx 40rpx 0rpx
  border-radius 10rpx
  margin-right 74rpx
}
.comeType:nth-child(4n){
  margin-right 0rpx
  /* outline 1px solid pink */
}


.comeTypeIcon{
  width: 90rpx;
  height: 90rpx;
  /* background: #1086FF; */
  margin 0rpx 0rpx 10rpx 0rpx
}
.comeTypeMsg{
  font-size: 26rpx;
  color: #333333;
  white-space nowrap
}
.comeTypeSel
  color #00A2FF
  font-weight bold
.memberItSt{
  color: #FF6E5D;
}
.memberItSt.empty{
  color #FFFFFF
}
.comeTimeBol{
  font-weight bold
}

.comeRight
  display flex
  align-items center
  padding 0rpx 10rpx 0rpx 0rpx
  margin-left auto
  text-align right
  /* border 1rpx solid blue */
.memberItIn{
  width: 422rpx;
}
.comeRightCarNO{
  display flex
  align-items center
  padding 0rpx 10rpx 0rpx 0rpx
  margin-left auto
  /* border 1rpx solid blue */
}
.rightCarNO{

}

.search-car-input {
    position: relative;
    margin-left auto
    width: 360rpx;
    /* height: 50rpx; */
    background: #FFFFFF;
    /* border 1rpx solid fuchsia */

    .car-input {
        float: right;
        display: flex;
        /* border 1rpx solid blue */

        //输入的车牌
        .car-input-text {
            float: left;
            color: #999;
            padding-right 6rpx;
        }
        .car-input-text.active{
          color #333
        }

        //新能源标识图
        .energy {
            float: left;
            /* width: 48rpx; */
            height: 34rpx;
            line-height: 32rpx;
            font-size: 26rpx;
            vertical-align: middle;
            align-self: center;
            margin-right: 18rpx;
            padding 0rpx 10rpx 0rpx 10rpx
            background #0AC160
            color #fff
            border 6rpx;
            white-space nowrap
        }

    }
}

.cursor{
    position: relative;
}

.cursor:after {
  position: absolute;
	content: '';
	display: inline-block;
	width: 2rpx;
	height: 28rpx;
	top: 50%;
	transform: translateY(-50%);
	animation: blink 1.2s infinite steps(1, start);
}

@-webkit-keyframes blink {
    0%, 100% {
        background-color: #000;
    }
    50% {
        background-color: transparent;
    }
}

.comePic
  margin-left 40rpx
  /* border 1rpx solid coral */
.comePicInput
  display inline-block
  vertical-align top
  width 60rpx
  text-align center
  margin 0rpx 10rpx 0rpx 10rpx
  /* border 1rpx solid aqua */
.comePicVie
  display inline-block
  /* width: 28rpx; */
  height: 24rpx;
  margin-right 10rpx
.comeDefault{
  color: #999;
}
.comePicDatIm{
  width: 28rpx;
  height: 24rpx;
  /* background: #1086FF; */
  margin 34rpx 0rpx 0rpx 0rpx
}


.comePicMain{
  position relative
  /* border 1rpx solid darkcyan */
}
.comePicDel
  position relative
  display inline-block
  vertical-align top
  margin 30rpx 0rpx 0rpx 10rpx
  height: 20rpx;
  width: 20rpx;
  transform: rotate(135deg);
  border-top: 2rpx solid #1086FF;
  border-right: 2rpx solid #1086FF;
.comePicDel.comeCarNo{
  margin 30rpx 16rpx 0rpx 6rpx
}
.btOne
  margin 90rpx 20rpx 24rpx 20rpx
.btOne.btDefalt{
  opacity 0.6
}
.comeMes{
  display flex
  align-items center
  width: 100%;
  /* height: 60rpx; */
  background: #F2F8FF;
  box-shadow: 4px 4px 22px 4px #F3F3F3, 0px 1px 0px 0px #B8DCFF;
  border-radius: 10rpx;
  font-size 22rpx
  color: #577C93;
  padding 10rpx 0rpx 10rpx 10rpx
  margin-top 0rpx
}

.remote
  padding 40rpx 30rpx 20rpx 30rpx
  .remoteMain
    position relative
    display flex
    flex-direction column
    justify-content center
    box-shadow: 4px 4px 22px 2px rgba(212, 212, 212, 0.39);
    width: 100%;
    height 120rpx;
    border-radius: 10rpx;
    padding 0rpx 20rpx 0rpx 116rpx
    background: #FFFFFF;
    /* border 1px solid #666 */
    margin-bottom 20rpx;
    z-index 0
    .remoteIco
      position absolute
      top 50%
      left 40rpx
      margin-top -25rpx
      width: 56rpx;
      height: 46rpx;
      background: #84D7FF;
      /* border 1px solid #84D7FF */
    .remoteSel
      position absolute
      bottom 0rpx
      right 0rpx
      width: 56rpx;
      height: 36rpx;
      /* border 1px solid #84D7FF */
.remoteGate{
  font-size: 30rpx;
  color: #030303;
  line-height: 42rpx;
}
.remoteName{
  font-size: 26rpx;
  color: #92A7B3;
}
.remoteBac{
  position absolute
  width: 100%;
  width: 100%;
  top 0rpx
  left 0rpx
  z-index -1
}
.movableArea{
  position fixed
  top 100rpx
  left 0rpx
  width 750rpx
  height 90vh
  background-color red
  z-index -1
}
.movableView{
  position absolute
  bottom 100rpx
  right 10rpx
  width 110rpx
  height 110rpx
  background blue
  border-radius 50%
}
.comePicImg{
  position absolute
  bottom 100rpx
  right 10rpx
  width: 28rpx;
  height: 24rpx;
  background: #1086FF;
  margin 25rpx 0rpx 0rpx 0rpx
}
.roomMov {
    position: fixed;
    width: 130rpx;
    height: 130rpx;
    right: 50rpx;
    bottom 100rpx
    line-height: 34rpx;
    font-size: 28rpx;
    /* background: #f00; */
    z-index: 1000;
}
.roomMov.reboot{
  bottom 258rpx
}
.roomMovTe {
  position absolute
  width: 130rpx;
  height: 130rpx;
  top 50%
  left 50%
  margin-left -65rpx
  margin-top -65rpx
  z-index -1
}
.roomMovMsg{
  color #fff;
  text-align center
  line-height 130rpx
  font-size 28rpx
  font-weight bold
}

.appEmp{
  display flex
  flex-direction column
  align-items center
  height 100vh
  background #fff
  margin: -110rpx 0rpx 0rpx 0rpx;
  padding: 210rpx 0rpx 0rpx 0rpx;
}
.appEmpIcon{
  width: 670rpx;
  height: 730rpx;
  // border 1rpx solid aqua
}
.appEmpMsg{
  color: #A8AFB6;
  font-size: 36rpx;
  margin: -183rpx 0rpx 0rpx 0rpx;
}
</style>
